package security.mobile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Component;

import security.handler.FailAuthenticationHandler;
import security.handler.SuccessAuthenticationHandler;

/**
 * 手机认证的配置
 * 
 * @author majie
 *
 */
@Component
public class MobileAuthenticationSecurityConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity>{
	
	@Autowired
	private UserDetailsService userDetailsService;
	
	@Autowired
	private SuccessAuthenticationHandler successAuthenticationHandler;
	
	@Autowired
	private FailAuthenticationHandler failAuthenticationHandler;
	
	@Override
	public void configure(HttpSecurity http) throws Exception {
		
		MobileAuthenticationFilter mobileAuthenticationFilter = new MobileAuthenticationFilter();
		mobileAuthenticationFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
		mobileAuthenticationFilter.setAuthenticationSuccessHandler(successAuthenticationHandler);
		mobileAuthenticationFilter.setAuthenticationFailureHandler(failAuthenticationHandler);
		
		MobileAuthenticationProvider mobileAuthenticationProvider = new MobileAuthenticationProvider();
		mobileAuthenticationProvider.setUserDetailsService(userDetailsService);
		
		http.authenticationProvider(mobileAuthenticationProvider)
			.addFilterAfter(mobileAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
	}
	
}
